/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.applis.demo.actions;

import opiam.admin.applis.demo.beans.Person;
import opiam.admin.applis.demo.forms.PersonForm;

import opiam.admin.faare.SearchResult;
import opiam.admin.faare.service.UserContext;
import opiam.admin.faare.service.javabeans.Criteria;
import opiam.admin.faare.service.javabeans.SearchArgument;
import opiam.admin.faare.service.services.SortService;
import opiam.admin.faare.service.services.StandardService;
import opiam.admin.faare.struts.actions.SecureAction;
import opiam.admin.faare.struts.utils.SessionContext;

import org.apache.log4j.Logger;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;

import java.util.ArrayList;
import java.util.List;


/**
 * This class allows to search the users list corresponding to the manager field filter,
 * and display it.
 */
public class ShowUsersAction extends SecureAction
{
    /** Instance of the log4j logger.
     * Used to generate the execution traces. */
    private static Logger _logger =
        Logger.getLogger(ProfileAction.class.getName());

    /**
     * This method is called to execute the action.
     *
     * @param mapping              Struts mapping data.
     * @param actionForm           FormBean associated with the action.
     * @param request              HTTP request.
     * @param httpServletResponse  HTTP response.
     *
     * @return An ActionForward.
     *
     * @throws IOException  An I/O exception if failed or interrupted I/O operations occurs.
     * @throws ServletException  A ServletException if the servlet has a problem.
     */
    @Override
	public ActionForward secureExecute(ActionMapping mapping,
                                       ActionForm actionForm,
                                       HttpServletRequest request,
                                       HttpServletResponse httpServletResponse
                                      ) throws IOException, ServletException
    {
        SessionContext sessionContext = null;
        UserContext userContext = null;
        ActionMessages msgErrors = new ActionMessages();

        try
        {
            // Gets the session.
            HttpSession session = request.getSession();

            // Gets the session context.
            sessionContext = SessionContext.getInstance(session);

            // Gets the user context.
            userContext = sessionContext.getUserContext();

            // Connected user
            Person cuser = (Person) userContext.getJbUser();

            // Gets the profile
            String profile = cuser.getProfile();

            String sessionResultName = "usersSearchResult";

            // Removes the "usersSearchResult" attribute in the session.
            session.removeAttribute(sessionResultName);

            String userCN = ((PersonForm) actionForm).getManager();

            // Checks if the field is not empty.
            // Returns to the search page if the field is empty.
            if ((userCN == null) ||
                    (userCN.trim().compareToIgnoreCase("") == 0)
               )
            {
                if (profile.equals("Accounting Manager") ||
                        profile.equals("HR Manager") ||
                        profile.equals("PD Manager") ||
                        profile.equals("QA Manager")
                   )
                {
                    return (mapping.findForward("noarg_manager"));
                }
                else if (profile.equals("Directory Administrator"))
                {
                    return (mapping.findForward("noarg_directoryadministrator"));
                }
            }

            // Creates the search parameters
            Criteria c1 = Criteria.getAndInstance();
            c1.addContains("commonName", userCN);

            SearchArgument arg =
                new SearchArgument(c1,
                                   userContext.findJBRessourceByName("Person"),
                                   userContext
                                  );

            List args = new ArrayList();
            args.add(arg);

            // Calls the StandardService to search the entries.
            SearchResult searchResult =
                StandardService.search(args, userContext);

            // writes the results number on the output defined in the
            // logger_config.properties.
            _logger.debug("***** result size = " +
                          searchResult.getLResults().size()
                         );

            boolean oneman = false;

            // If there is only one result, returns the visualization page.
            if (searchResult.getLResults().size() == 1)
            {
                // Gets the entry.
                Object loadedObj = searchResult.getLResults().get(0);

                // Sets the found entry in the session.
                Person person = (Person) loadedObj;
                PersonForm pf = (PersonForm) actionForm;
                pf.setManagerPerson(person);
                pf.setManager(person.getCommonName());

                oneman = true;
            }

            String forward = "success";

            if (oneman)
            {
                if (profile.equals("Accounting Manager") ||
                        profile.equals("HR Manager") ||
                        profile.equals("PD Manager") ||
                        profile.equals("QA Manager")
                   )
                {
                    forward = "success_one_manager";
                }
                else if (profile.equals("Directory Administrator"))
                {
                    forward = "success_one_directoryadministrator";
                }
            }
            else
            {
                // Calls the SortService to sort the results list according to the
                // "name" attribute.
                SortService.sort(searchResult.getLResults(), Person.class,
                                 "name", userContext
                                );

                // Sets the result of the search on the session.
                session.setAttribute(sessionResultName, searchResult);

                if (profile.equals("Accounting Manager") ||
                        profile.equals("HR Manager") ||
                        profile.equals("PD Manager") ||
                        profile.equals("QA Manager")
                   )
                {
                    forward = "success_manager";
                }
                else if (profile.equals("Directory Administrator"))
                {
                    forward = "success_directoryadministrator";
                }
            }

            // Returns the URI corresponding to the action success
            // as defined in the action configuration in the struts-config.xml.
            return (mapping.findForward(forward));
        }
        catch (Exception se)
        {
            _logger.error(se.getMessage());
            msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                          new ActionMessage("error.service.unknown")
                         );
            saveErrors(request, msgErrors);

            return (mapping.findForward("service_error"));
        }
    }
}
